<?php
namespace Common\Model;
use Think\Model;
class CustLocationModel extends Model {
	protected $connection = 'DB_BASE_DSN';
	protected $tableName = 'qyx_cust_location'; 
	
	public function addLocation($data){
		$map['custid'] = $data['custid'];
		$ret = $this->where($map)->find();
		if(!empty($ret)){
			$data['updatetime'] = date("Y-m-d H:i:s");
			$data['times'] = $ret['times'] + 1;
			$result = $this->where($map)->save($data);
			if($result) return $data['custid'];
		}else{
			$result = $this->add($data);
		}
		
		return $result;
	}
	
	
	public function getCustLocation($custid){
		$map['custid'] = $custid;
		$result = $this->where($map)->find();
		return $result;
	}
	
	
	public function getGEOCust($geoinStr, $length, $limit = 50 , $sex = null){
		if($sex === "0" || $sex === "1"){
			$sql = "SELECT a.custid,a.longitude,a.latitude,a.updatetime FROM {$this->tableName} a ,qyx_cust b WHERE a.custid=b.custid and b.sex={$sex} and b.custtype=1";
			if (!empty($geoinStr) && $length > 0) {
				$sql .= " AND LEFT(a.geohash, {$length}) IN({$geoinStr})";
			}
			$sql .= " ORDER BY a.updatetime DESC LIMIT {$limit}";
		}else{
			$sql = "SELECT a.custid,a.longitude,a.latitude,a.updatetime FROM {$this->tableName} a ,qyx_cust b WHERE a.custid=b.custid and b.custtype=1";
			if (!empty($geoinStr) && $length > 0) {
				$sql .= " AND LEFT(a.geohash, {$length}) IN({$geoinStr})";
			}
			$sql .= " ORDER BY a.updatetime DESC LIMIT {$limit}";
		}
		
		$result = $this->query($sql);
		return $result;
	}
	
	public function getCustLocationList($data){
		$map = array();
		if(!empty($data['custid'])){
			if(is_array($data['custid']))
				$map['custid']  = array('in',$data['custid']);
			else 
				$map['custid']  = $data['custid'];
		}
		
		$result = $this->where($map)->select();
		
		return $result;
	}
	
	
	public function deleteLocation($custid){
		$map['custid'] = $custid;
		$result = $this->where($map)->delete();
		return $result;
	}
	
}


